package controllers

import (
	"beego/models"
	"beego/tool"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/gomodule/redigo/redis"
	"time"
)

var pool *redis.Pool
var stockMap = make(map[string]int)
var isExpire bool
var reqDur time.Duration
var timeOurDur time.Duration

type StockController struct {
	beego.Controller
}

func (c *StockController) Get() {
	id := c.Ctx.Input.Param(":id")
	AfterStock()
	stock, err := GetRedis(id, c)
	if err != nil {
		GetOriStockForFirst(id, c)
	} else {
		c.Data["json"] = Transfer(stock)
		c.ServeJSON()
	}
	//isExist, ok := stockMap[id]
	//if ok {
	//	if isExist == 0 {
	//		stockMap[id] = 1
	//		go RepeatGetOriStock(id, reqDur)
	//	}
	//} else {
	//	stockMap[id] = 1
	//	go RepeatGetOriStock(id, reqDur)
	//}
}

func Transfer(stock []byte) *models.StockRes {
	var stockJson models.StockJson
	err := json.Unmarshal(stock, &stockJson)
	stockData := stockJson.Data.List[0]
	var stockDetails models.StockDetails
	stockDetails.Rate = stockData.Stock.PriceLimit
	stockDetails.NowPrice = stockData.Stock.PriceLimit
	res := models.StockRes{StockName: stockData.Stock.Name, StockId: stockData.Stock.Symbol, SD: stockDetails}
	if err != nil {
		fmt.Println(err)
	}
	return &res
}

func AfterStock() {
	if time.Now().Hour() > 15 || time.Now().Hour() < 9 {
		isExpire = false
		reqDur = time.Hour * 5
		timeOurDur = time.Hour * 5
	} else {
		isExpire = true
		reqDur = time.Second * 1
		timeOurDur = time.Second * 60
	}
}
func init() {
	pool = &redis.Pool{
		MaxIdle:     16,
		MaxActive:   1024,
		IdleTimeout: 300,
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", "localhost:6379")
		},
	}
}
func RepeatGetOriStock(id string, dur time.Duration) {
	timeout := Timer(timeOurDur)
	tick := time.Tick(dur)
	for {
		select {
		case <-timeout:
			stockMap[id] = 0
			fmt.Print("退出")
			fmt.Println(time.Now())
			return
		case <-tick:
			fmt.Print("开始")
			fmt.Println(time.Now())
			GetOriStock(id)
		}
	}
}
func GetOriStockForFirst(id string, c *StockController) {
	market := id[:2]
	symbol := id[2:]
	url := "https://hq.chongnengjihua.com/rjhy-gmg-quote/api/1/stock/articlesv2?" +
		"market=" + market + "&symbol=" + symbol + "&pageNo=0&pageSize=1&types=2"
	SetRedis(tool.SendGetRQ(url), id)
	stock, _ := GetRedis(id, c)
	c.Data["json"] = Transfer(stock)
	c.ServeJSON()
}

func GetOriStock(id string) {
	market := id[:2]
	symbol := id[2:]
	url := "https://hq.chongnengjihua.com/rjhy-gmg-quote/api/1/stock/articlesv2?" +
		"market=" + market + "&symbol=" + symbol + "&pageNo=0&pageSize=1&types=2"
	SetRedis(tool.SendGetRQ(url), id)
}

func SetRedis(bytes []byte, id string) {
	c := pool.Get()
	defer c.Close()
	_, err := c.Do("Set", id, bytes)
	if isExpire {
		fmt.Println("expire")
		_, err = c.Do("expire", id, 10)
	}
	if err != nil {
		fmt.Println("SetRedis")
		fmt.Println(err)
		return
	}
}
func GetRedis(id string, c *StockController) ([]byte, error) {
	connect := pool.Get()
	defer connect.Close()
	r, err := redis.Bytes(connect.Do("Get", id))
	return r, err
}
func Timer(duration time.Duration) chan bool {
	ch := make(chan bool)
	go func() {
		time.Sleep(duration)
		ch <- true
	}()
	return ch
}
